package com.api.qfengx.data.mode;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.weaver.qfengx.DaoUtils;
import com.weaver.qfengx.NumberUtils;
import com.weaver.qfengx.RequestUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.config.DevModeConfig;
import com.weaver.qfengx.entity.PageInfo;
import com.weaver.qfengx.entity.PageQuery;
import com.weaver.qfengx.entity.Result;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 建模数据抽取Api
 * @Author Opp
 * @Date 2023-03-01 00:50
 */
@Path("/qfengx/data/mode")
public class ModeDataApi {

    /**
     * 如果存在base64 则优先获取base64, 没有则获取默认的
     * @param queryId
     * @return
     */
    private String getSqlWhere(String queryId) {
        String whereSql = DevModeConfig.getPropConfig("data.mode.query.base64.where." + queryId, "").getValue();
        if (StrUtil.isNotBlank(whereSql)) {
            return Base64.decodeStr(whereSql);
        }
        return DevModeConfig.getPropConfig("data.mode.query.where." + queryId, "").getValue();
    }

    @GET
    @Path("/listAll")
    @Produces(MediaType.APPLICATION_JSON)
    public String listAll(@Context HttpServletRequest request) {
        try {
            Map<String, Object> paramsMap = RequestUtils.getParamsMap(request);
            String queryId = StringUtils.val(paramsMap.get("queryId"));
            if (StringUtils.isBlank(queryId)) {
                return JSON.toJSONString(Result.fail("queryId为空"));
            }
            String tablename = DevModeConfig.getPropConfig("data.mode.query.tblname." + queryId, "").getValue();
            if (StringUtils.isBlank(tablename)) {
                return JSON.toJSONString(Result.fail("queryId未配置"));
            }

            String whereSql = getSqlWhere(queryId);
            String fieldname = DevModeConfig.getPropConfig("data.mode.query.fields." + queryId, " * ").getValue();
            return JSON.toJSONString(Result.ok(DaoUtils.executeQueryToMapList(String.format("select %s from %s ", fieldname, tablename) + whereSql)));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

    /**
     * 详细明细查询
     * @param request
     * @return
     */
    @GET
    @Path("/info")
    @Produces(MediaType.APPLICATION_JSON)
    public String info(@Context HttpServletRequest request) {
        Map<String, Object> paramsMap = RequestUtils.getParamsMap(request);
        String queryId = StringUtils.val(paramsMap.get("queryId"));
        String id = StringUtils.val(paramsMap.get("id"));
        if (StringUtils.isBlank(queryId) || StringUtils.isBlank(id)) {
            return JSON.toJSONString(Result.paramErr());
        }
        String tablename = DevModeConfig.getPropConfig("data.mode.query.tblname." + queryId, "").getValue();
        if (StringUtils.isBlank(tablename)) {
            return JSON.toJSONString(Result.fail("queryId未配置"));
        }
        String fieldname = DevModeConfig.getPropConfig("data.mode.queryinfo.fields." + queryId, " * ").getValue();

        Map<String, String> infoData = DaoUtils.executeQueryToMap(String.format("select %s from %s where id = ?", fieldname, tablename), id);
        if (Objects.isNull(infoData) || infoData.isEmpty()) {
            return JSON.toJSONString(Result.ok(infoData));
        }
        // 查询并添加所有可能的明细
        List<Map<String, String>> dtMapList =
                DaoUtils.executeQueryToMapList("select * from workflow_billdetailtable " +
                        "where billid = (select id from workflow_bill where tablename= ?) order by orderid", tablename);
        Map<String, Object> resData = Maps.newHashMap(infoData);
        for (Map<String, String> dtMap : dtMapList) {
            String dtTblName = dtMap.get("tablename");
            if (StrUtil.isBlank(dtTblName)) continue;
            String orderid = dtMap.get("orderid");
            String dtFields = DevModeConfig.getPropConfig("data.mode.querydt." + orderid + ".fields." + queryId, " * ").getValue();
            List<Map<String, String>> dtData = DaoUtils.executeQueryToMapList(String.format("select %s from %s where mainid = ?", dtFields, dtTblName), id);
            resData.put("dt_" + orderid, dtData);
        }
        return JSON.toJSONString(Result.ok(resData));
    }

    @GET
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String list(@Context HttpServletRequest request) {
        try {
            Map<String, Object> paramsMap = RequestUtils.getParamsMap(request);
            String queryId = StringUtils.val(paramsMap.get("queryId"));
            String page = StringUtils.val(paramsMap.get("page"));
            String limit = StringUtils.val(paramsMap.get("limit"));
            Integer currentPage = NumberUtils.parseInt(page, 1);
            Integer pageSize = NumberUtils.parseInt(limit, 10);
            if (StringUtils.isBlank(queryId)) {
                return JSON.toJSONString(Result.fail("queryId为空"));
            }
            String tablename = DevModeConfig.getPropConfig("data.mode.query.tblname." + queryId, "").getValue();
            if (StringUtils.isBlank(tablename)) {
                return JSON.toJSONString(Result.fail("queryId未配置"));
            }
            String fieldname = DevModeConfig.getPropConfig("data.mode.query.fields." + queryId, " * ").getValue();
            String whereSql = getSqlWhere(queryId);
            PageQuery pageQuery = new PageQuery(currentPage, pageSize);
            PageInfo<Map<String, String>> mapPageInfo = DaoUtils.executePageMapList(String.format("select %s from %s ", fieldname, tablename) + whereSql, pageQuery);
            return JSON.toJSONString(Result.ok(mapPageInfo));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

}
